import { useState, useEffect, useCallback } from 'react';
import { message } from 'antd';
import { useDeepCompareEffect } from 'react-use';
import { getLocale } from 'umi';
import wfc from '@/chat/wfc/client/wfc';
import vvChat from '@/chat/vv-chat';
import EventType from '@/chat/wfc/client/wfcEvent';
import Msg from './Msg';

const WORK_IM_TYPE = 3009; // 3009跟IM约定的work业务编码

// 获取订阅类型的key
const getSubKey = v => {
    let temp;
    Object.entries(Msg).forEach(([key, value]) => {
        if (v === value?.code) {
            temp = key;
        }
    });
    return temp;
};

/**
 * @description 服务端消息接收，长链接通道，stomp为true时采用自建socket
 * @param {Object} subType 订阅类型，单个对象，或者对象数组
 * @returns 服务端推送过来的数据
 */
const useSubscribeMsg = ({ stomp = false, subType }) => {
    const [subContent, setSubContent] = useState();

    // 处理接收消息
    const handleReceiveMessage = useCallback(
        res => {
            const { type, content } = res?.content || {};
            console.log('IM通道消息体：', res);
            if (!subType) {
                return;
            }
            if (type === WORK_IM_TYPE) {
                try {
                    const { imType, data } = JSON.parse(content) || {};
                    const typeCodeArr = []; // 订阅类型code集合，用来判断信息是否在订阅的类型里面
                    const subTypeKey = getSubKey(imType); // 订阅类型对象key，用来区分信息所属类型
                    if (Array.isArray(subType)) {
                        subType.forEach(item => {
                            typeCodeArr.push(item.code);
                        });
                    } else {
                        typeCodeArr.push(subType.code);
                    }

                    if (typeCodeArr.includes(imType)) {
                        setSubContent({ ...data, type: subTypeKey }); // 后端会返回data，这个值变更说明有新的消息
                    }
                } catch {
                    // 错误提示
                    const userLanguage = getLocale();
                    message.error(
                        Object.keys(subType.errorMsg).includes(userLanguage)
                            ? `${subType.errorMsg[userLanguage]}`
                            : `${subType.errorMsg.zh_CN}`
                    );
                }
            }
        },
        [subType]
    );

    // 处理自建socket逻辑,返回值保持与野火IM一致
    const handleVVChatMessage = useCallback(({ msg }) => {
        const { data, imType } = JSON.parse(msg?.body || '{}');
        const subTypeKey = getSubKey(imType);
        setSubContent({ data, type: subTypeKey });
    }, []);

    // 订阅自建socket通道消息，目前尚未完成stompJS的取消订阅
    useDeepCompareEffect(() => {
        if (stomp) {
            let code;
            if (Array.isArray(subType)) {
                code = subType.map(i => i.code);
            } else {
                code = subType?.code;
            }
            vvChat.subscribe(code, handleVVChatMessage);
        }
    }, [handleVVChatMessage, stomp, subType]);

    // 订阅野火IM通道消息
    useEffect(() => {
        if (!stomp) {
            wfc.eventEmitter.on(EventType.ReceiveMessage, handleReceiveMessage);
        }
        return () => {
            if (!stomp) {
                wfc.eventEmitter.removeListener(EventType.ReceiveMessage, handleReceiveMessage);
            }
        };
    }, [handleReceiveMessage, stomp]);
    return { subContent };
};

export default useSubscribeMsg;
